package com.black.auth.authority;

import com.black.common.feign.PlatformFeignClient;
import com.black.common.vo.ShareUserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @author linwenfeng
 */
@Service
@Primary
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserDetailsServiceImpl implements UserDetailsService {

    private final PlatformFeignClient platformFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ShareUserVo loginUser = this.platformFeignClient.findUserByUsername(username).getResult();
        if (loginUser == null) {
            throw new BadCredentialsException("用户名[" + username + "]不存在");
        } else {
            User user = new User(loginUser.getUsername(), loginUser.getPassword(),
                    AuthorityUtils.NO_AUTHORITIES);
            return new OauthUser(user, loginUser);
        }
    }
}
